package com.txl.tvluancher;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import java.io.InputStream;

public class WebFragment extends Fragment {

    private WebView webView;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.web_fragment,container,false);
    }

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        webView = getView().findViewById(R.id.webView);

        WebView.setWebContentsDebuggingEnabled(true);
        WebSettings settings = webView.getSettings();
        //设置编码
        settings.setDefaultTextEncodingName("utf-8");
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setDatabaseEnabled(true);
        settings.setAllowContentAccess(true);
        settings.setAllowFileAccess(true);
        settings.setAllowUniversalAccessFromFileURLs(true);
        settings.setSupportZoom(false);

        webView.setWebViewClient(new WebViewClient(){
            @Nullable
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                String url = request.getUrl().toString();
                if(url.startsWith("clienticon:")){
                    String pkm = url.substring(url.indexOf(":")+1);
                    InputStream inputStream = JSInterface.getInstance().loadIcon(pkm);
                    return new WebResourceResponse("image/png","utf-8",inputStream);
                }

                return super.shouldInterceptRequest(view, request);
            }
        });


        JSInterface jsInterface = JSInterface.getInstance();
        jsInterface.setWebView(webView);
        webView.addJavascriptInterface(jsInterface,"andClient");
        webView.loadUrl("file:///android_asset/index.html");

    }

    @Override
    public void onStart() {
        super.onStart();
        JSInterface.getInstance().stateChange("onStart","0");
    }

    @Override
    public void onStop() {
        super.onStop();
        JSInterface.getInstance().stateChange("onStop","0");
    }

    public WebView getWebView(){
        return webView;
    }
}
